package com.zhouheng.common.config;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * Slave数据源配置
 *
 * @MapperScan 扫描Mapper 接口并容器管理
 *
 * @author 周恒
 * @date 20180830 15:41:53
 * @since v1.0
 */
@Configuration
@MapperScan(basePackages = "com.zhouheng.module.multipledatasource.slave.**.dao", sqlSessionFactoryRef = "slaveSqlSessionFactory")
public class SlaveDataSourceConfig {

    private SlaveDataSourceProperty slaveDataSourceProperty;

    public SlaveDataSourceConfig(SlaveDataSourceProperty slaveDataSourceProperty) {
        this.slaveDataSourceProperty = slaveDataSourceProperty;
    }

    @Bean(name = "slaveDataSource")
    @ConditionalOnMissingBean(HikariDataSource.class)
    public DataSource slaveDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(slaveDataSourceProperty.getDriverClassName());
        dataSource.setJdbcUrl(slaveDataSourceProperty.getUrl());
        dataSource.setUsername(slaveDataSourceProperty.getUserName());
        dataSource.setPassword(slaveDataSourceProperty.getPassWord());
        return dataSource;
    }

    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager() {
        return new DataSourceTransactionManager(slaveDataSource());
    }

    @Bean(name = "slaveSqlSessionFactory")
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource slaveDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(slaveDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/multipledatasource/slave/*.xml"));
        return sessionFactory.getObject();
    }

    @Bean(name = "slaveTransactionManager")
    public DataSourceTransactionManager slaveTransactionManager(@Qualifier("slaveDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name= "slaveSqlSessionTemplate")
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
